<script setup>
import { ref, watch } from 'vue'
import { store } from '../store.js'
import { generateAIResponse, handleAPIError } from '../services/AIService.js'

const showChat = ref(false)
const messages = ref([])
const userInput = ref('')
const isLoading = ref(false)

// 加载历史聊天记录
const loadHistory = () => {
  const savedMessages = store.aiChat.loadChatHistory()
  if (savedMessages && savedMessages.length > 0) {
    messages.value = savedMessages
  }
}

// 监听消息变化，自动保存
watch(messages, (newMessages) => {
  store.aiChat.saveChatHistory(newMessages)
}, { deep: true })

// 从AI服务获取响应
const getAIResponse = async (query) => {
  isLoading.value = true
  
  try {
    // 调用AI服务生成响应
    const response = await generateAIResponse(query)
    
    messages.value.push({
      type: 'ai',
      content: response
    })
  } catch (error) {
    // 错误处理
    const errorMessage = handleAPIError(error)
    messages.value.push({
      type: 'ai',
      content: errorMessage
    })
  } finally {
    isLoading.value = false
    
    // 自动滚动到底部
    setTimeout(() => {
      const chatContainer = document.querySelector('.chat-messages')
      if (chatContainer) {
        chatContainer.scrollTop = chatContainer.scrollHeight
      }
    }, 100)
  }
}

// 发送消息
const sendMessage = () => {
  if (userInput.value.trim() && !isLoading.value) {
    const message = userInput.value.trim()
    messages.value.push({
      type: 'user',
      content: message
    })
    
    userInput.value = ''
    
    // 调用AI获取回复
    getAIResponse(message)
  }
}

// 切换聊天窗口显示状态
const toggleChat = () => {
  showChat.value = !showChat.value
  
  if (showChat.value) {
    // 加载历史聊天记录
    loadHistory()
    
    // 如果没有消息，添加欢迎消息
    if (messages.value.length === 0) {
      messages.value.push({
        type: 'ai',
        content: '你好！我是游戏助手AI，我可以帮你搜索游戏相关的帖子。请告诉我你在玩什么游戏？'
      })
    }
  }
}

// 清除聊天记录
const clearChat = () => {
  if (confirm('确定要清除所有聊天记录吗？')) {
    messages.value = []
    store.aiChat.clearChatHistory()
    
    // 清除后添加欢迎消息
    messages.value.push({
      type: 'ai',
      content: '聊天记录已清除。有什么可以帮助你的吗？'
    })
  }
}

// 按Enter键发送消息
const handleKeyPress = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}
</script>

<template>
  <div class="ai-chatbot-container">
    <!-- 聊天按钮 -->
    <div 
      class="chatbot-toggle" 
      @click="toggleChat"
      :class="{ active: showChat }"
    >
      <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
        <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/>
      </svg>
      <span v-if="!showChat">AI助手</span>
      <span v-else>关闭</span>
    </div>
    
    <!-- 聊天窗口 -->
    <Transition name="chat-window">
      <div class="chat-window" v-if="showChat">
        <div class="chat-header">
        <div class="chatbot-avatar">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
          </svg>
        </div>
        <h3>游戏助手AI</h3>
        <div class="header-actions">
          <button class="clear-chat-button" @click="clearChat" title="清除聊天记录">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
            </svg>
          </button>
          <button class="close-button" @click="toggleChat" title="关闭">×</button>
        </div>
      </div>
        
        <div class="chat-messages">
          <div 
            v-for="(msg, index) in messages" 
            :key="index"
            :class="['message', msg.type]"
          >
            <div class="message-content">{{ msg.content }}</div>
          </div>
          
          <div v-if="isLoading" class="loading-message">
            <span>AI正在思考...</span>
          </div>
        </div>
        
        <div class="chat-input">
          <input
            v-model="userInput"
            @keypress="handleKeyPress"
            placeholder="输入消息..."
            :disabled="isLoading"
          />
          <button @click="sendMessage" :disabled="isLoading" class="send-button">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
              <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
            </svg>
          </button>
        </div>
      </div>
    </Transition>
  </div>
</template>

<style scoped>
.ai-chatbot-container {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

.chatbot-toggle {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #4a6cf7;
  color: white;
  border: none;
  border-radius: 50px;
  padding: 12px 20px;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(74, 108, 247, 0.3);
  transition: all 0.3s ease;
  font-weight: 500;
}

.chatbot-toggle:hover {
  background: #3a58d4;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(74, 108, 247, 0.4);
}

.chatbot-toggle.active {
  background: #f44336;
}

.chatbot-toggle.active:hover {
  background: #d32f2f;
}

.chat-window {
  width: 350px;
  max-height: 500px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  background: #4a6cf7;
  color: white;
}

.chatbot-avatar {
  width: 32px;
  height: 32px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chat-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  flex: 1;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.clear-chat-button {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background 0.2s;
}

.clear-chat-button:hover {
  background: rgba(255, 255, 255, 0.2);
}

.close-button {
  background: none;
  border: none;
  color: white;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background 0.2s;
}

.close-button:hover {
  background: rgba(255, 255, 255, 0.2);
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
  background: #f8f9fa;
}

.message {
  max-width: 85%;
  word-wrap: break-word;
  white-space: pre-line;
}

.message.user {
  align-self: flex-end;
}

.message.ai {
  align-self: flex-start;
}

.message-content {
  padding: 12px 16px;
  border-radius: 16px;
  font-size: 14px;
  line-height: 1.5;
}

.message.user .message-content {
  background: #4a6cf7;
  color: white;
  border-bottom-right-radius: 4px;
}

.message.ai .message-content {
  background: white;
  color: #333;
  border: 1px solid #e9ecef;
  border-bottom-left-radius: 4px;
}

.loading-message {
  align-self: flex-start;
  padding: 12px 16px;
  background: white;
  border-radius: 16px;
  border: 1px solid #e9ecef;
  font-size: 14px;
  color: #666;
}

.chat-input {
  display: flex;
  gap: 8px;
  padding: 16px;
  background: white;
  border-top: 1px solid #e9ecef;
}

.chat-input input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 24px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s;
}

.chat-input input:focus {
  border-color: #4a6cf7;
}

.chat-input input:disabled {
  background: #f8f9fa;
  cursor: not-allowed;
}

.send-button {
  background: #4a6cf7;
  color: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.send-button:hover:not(:disabled) {
  background: #3a58d4;
  transform: scale(1.05);
}

.send-button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 动画效果 */
.chat-window-enter-active,
.chat-window-leave-active {
  transition: all 0.3s ease;
}

.chat-window-enter-from,
.chat-window-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

/* 响应式调整 */
@media (max-width: 480px) {
  .chat-window {
    width: 90vw;
    max-width: none;
  }
}
</style>